#include "AnimationComponent.h"



AnimationComponent::~AnimationComponent()
{
	Ogre::Root::getSingleton().removeFrameListener(this);
}


void AnimationComponent::init()
{
	mGo = dynamic_cast<GameObject*>(mContainer);

	anim = new Object("animation");
	
	mEntity = mGo->getProperty<Entity*>("entity");

	mStates = mEntity->getAllAnimationStates();

	if(mEntity->hasSkeleton())
		{
//			mGo->addProperty<Object>("skeleton", skel);
			Ogre::SkeletonInstance* skel = mEntity->getSkeleton();
			skel->setBlendMode( Ogre::ANIMBLEND_CUMULATIVE );
		}

	AnimationStateIterator it = mStates->getAnimationStateIterator();
	while(it.hasMoreElements())
		{
			Ogre::AnimationState* state = it.getNext();
			Ogre::String name = state->getAnimationName();
			Object o("state");

			Property<bool>* p = new Property<bool>("enabled", false);

//		posCon = p->onChanged.connect( sigc::mem_fun(this, &AnimationComponent::enableState) );
//			p->onChanged.connect(sigc::bind( sigc::mem_fun(this, &AnimationComponent::setStateEnabled),  name, *p) );
			p->onChanged.connect(sigc::bind( sigc::mem_fun(this, &AnimationComponent::setStateEnabled),  name) );
			o.addProperty(static_cast<IProperty*>(p));

//			std::cout << name << std::endl;

			anim->addProperty<Object>(name, o);
		}

	mGo->addProperty<Object>("animation", *anim);

	Ogre::Root::getSingleton().addFrameListener(this);
}

bool AnimationComponent::frameStarted(const FrameEvent& evt)
{
	AnimationStateIterator it = mStates->getAnimationStateIterator();
	while(it.hasMoreElements())
		{
			AnimationState* state = it.getNext();
//		state->setEnabled(true);
			state->addTime(evt.timeSinceLastFrame);
		}
	return true;
}
